﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

using DotNetNuke.Entities.Modules;
using DesertedRoadStudios.BlogNetNuke.Common;
using DesertedRoadStudios.BlogNetNuke.Components;
using p = DesertedRoadStudios.BlogNetNuke.Entities.Post;
using c = DesertedRoadStudios.BlogNetNuke.Entities.Category;
using t = DesertedRoadStudios.BlogNetNuke.Entities.Tag;

namespace DesertedRoadStudios.BlogNetNuke.UI.Widgets
{
    public class LatestPosts : PortalModuleBase
    {
        private IEnumerable<PostInfo> _posts;
        private List<Post> _postList;
        private XDocument _settings;
        private Dictionary<string, string> _widgetSettings;

        public IEnumerable<Post> Posts { get { return _postList.AsEnumerable(); } }

        public class Post : p.PostInfo
        {
            private List<c.CategoryInfo> _categories;
            private List<t.TagInfo> _tags;
            private XDocument _settings;
            private System.Web.HttpContext _context;
            
            public Post(System.Web.HttpContext context, XDocument settings)
            {
                _context = context;
                _settings = settings;
            }

            public List<c.CategoryInfo> Categories 
            { 
                get { return _categories; }
                set { _categories = value; }
            }
            
            public List<t.TagInfo> Tags 
            { 
                get { return _tags; }
                set { _tags = value; }
            }
            
            public string RelativeURL { get { return _settings.Element("params").Element("Blog").Element("BlogDetails").Element("TabPath").Value.Replace("//", "/") + Methods.GetPathExtension(_settings, PostPath); } }
            public string AbsoluteURL { get { return (_context.Request.IsSecureConnection ? "https://" : "http://") + _context.Request.Url.Host + _settings.Element("params").Element("Blog").Element("BlogDetails").Element("TabPath").Value.Replace("//", "/") + Methods.GetPathExtension(_settings, PostPath); } }
            public string PermaLink { get { return (_context.Request.IsSecureConnection ? "https://" : "http://") + _context.Request.Url.Host + Methods.GetPathExtension(_settings, TabPath.Replace("//", "/")) + "?postID=" +  PostID; } }
            
            public DotNetNuke.Entities.Users.UserInfo Author { get { return DotNetNuke.Entities.Users.UserController.GetUserById(PortalID, AuthorID); } }

        }

        public LatestPosts()
        {
        }

        public LatestPosts(XDocument settings, Dictionary<string, string> widgetSettings, IEnumerable<PostInfo> posts)
        {
            _settings = settings;
            _widgetSettings = widgetSettings;
            _posts = posts;
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            CheckWidget();
            
            _postList = new List<Post>();
            BlogNetNukeController bnn = new BlogNetNukeController();

            foreach (PostInfo pInfo in _posts)
            {
                Post post = new Post(Context, _settings);
                pInfo.CopyTo((p.PostInfo)post);

                List<c.CategoryInfo> categories = new List<c.CategoryInfo>();
                foreach (PostsCategories category in bnn.GetAllCategoriesForPosts(pInfo.PortalID, pInfo.ModuleID).Where(c => c.PostID == pInfo.PostID))
                    categories.Add(new c.CategoryInfo()
                    {
                        Category = category.Category,
                        CategoryID = category.CategoryID,
                        Description = category.Description,
                        Keywords = category.Keywords,
                        ModuleID = category.ModuleID,
                        ParentID = category.ParentID,
                        PortalID = category.PortalID,
                        Slug = category.Slug,
                        CategoryLink = Methods.GetPathExtension(_settings, _settings.Element("params").Element("Blog").Element("BlogDetails").Element("TabPath").Value.Replace("//", "/") + "/Category/" + category.Slug)
                    });

                List<t.TagInfo> tags = new List<t.TagInfo>();
                foreach (PostsTags tag in bnn.GetAllTagsForPosts(pInfo.PortalID, pInfo.ModuleID).Where(t => t.PostID == pInfo.PostID))
                    tags.Add(new t.TagInfo()
                    {
                        Tag = tag.Tag,
                        TagID = tag.TagID,
                        ModuleID = tag.ModuleID,
                        PortalID = tag.PortalID,
                        Slug = tag.Slug,
                        TagLink = Methods.GetPathExtension(_settings, _settings.Element("params").Element("Blog").Element("BlogDetails").Element("TabPath").Value.Replace("//", "/") + "/Tag/" + tag.Slug)
                    });

                post.Categories = categories;
                post.Tags = tags;
                _postList.Add(post);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        private void CheckWidget()
        {
            if (!_widgetSettings["Widget"].Equals("LatestPosts"))
                throw new System.Exception("Control doesn't implement DesertedRoadStudios.BlogNetNuke.UI.Widgets." + _widgetSettings["Widget"]);

            if (!_widgetSettings.ContainsKey("MaximumPosts") || string.IsNullOrEmpty(_widgetSettings["MaximumPosts"]))
                _posts = _posts.Take(5);
            else
                _posts = _posts.Take(Convert.ToInt32(_widgetSettings["MaximumPosts"]));

        }
    }
}